<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use app\common\service\BaseService;
use think\exception\ValidateException;
use think\facade\Db;
use app\api\service\Topic as TopicService;
use app\common\model\Topic as TopicModel;
use app\common\model\Post as PostModel;
use app\common\model\User as UserModel;

class Topic extends ApiBase
{
    public function list()
    {
        $classId = input("class_id");
        $keyword = input("keyword");

        $where = [];
        if ($classId) {
            $where[] = ["class_id", "=", $classId];
        }

        if ($keyword) {
            $where[] = ["name", "like", "%" . $keyword . "%"];
        }

        $list = TopicModel::getList($where);

        return message($list);
    }

    //分类列表
    public function classList()
    {
        $list = Db::name("category")->select();
        return message($list);
    }

    //根据用户ID查询加入的圈子列表
    public function userJoinTopic()
    {
        $userId = input("user_id");

        $topicService = new TopicService();
        $list = $topicService->getUserTopic($userId);
        return message($list);
    }

    //当前登录用户加入的圈子列表
    public function currentUserJoinTopic()
    {
        $userId = BaseService::getLoginUserIdNoAuth();

        $topicService = new TopicService();
        $list = $topicService->getUserTopic($userId, 1000);
        return message($list);
    }

    //热门圈子
    public function hot()
    {
        $count = input('count');
        $list = TopicModel::withJoin(["userInfo"])->order('post_num')->limit($count)->select();
        return message($list);
    }

    //圈子列表，显示最新三条帖子图片
    public function classTopicAreImg()
    {
        $classId = input("class_id");

        $where = [];
        if ($classId > 0) {
            $where[] = ["class_id", "=", $classId];
        }

        $list = Db::name("topic")->where($where)->order("post_num desc")->paginate(10)->each(function ($item) {

            $imgList = [];

            $postList = PostModel::where("type", '=', 1) //只查询图文帖子
            ->where("media", "<>", "[]")
                ->where("topic_id", "=", $item["id"])
                ->order("id desc")
                ->field("media")
                ->limit(3)
                ->select();

            foreach ($postList as $item2) {
                array_push($imgList, $item2["media"][0]);
            }

            $item["img_list"] = $imgList;
            $item["post_num"] = Db::name("post")->where("topic_id", "=", $item["id"])->count();

            return $item;

        });

        return message($list);
    }

    //圈子详情
    public function detail()
    {
        $id = input("id");
        $userId = BaseService::getLoginUserIdNoAuth();
        $detail = TopicModel::withJoin(["userInfo"])->find($id);

        $userIds = Db::name("user_topic")->where("topic_id", $id)->column('user_id');

        $adminUid = Db::name("topic_admin")->where("topic_id", $id)->column("user_id");
        $detail["admin_list"] = UserModel::order("update_time desc")->where("id", "in", $adminUid)->limit(9)->select($userIds)->each(function ($item) use ($userId) {
            $where["userId"] = $userId;
            $where["follow_uid"] = $item["id"];

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 0; //未关注
            }

            return $item;
        });

        //置顶帖子
        $postIds = Db::name("topic_top")->where("topic_id", $id)->column("post_id");
        $detail["top_post"] = Db::name("post")->where("id", "in", $postIds)->select();

        if ($userId) {
            $where[] = ["user_id", "=", $userId];
            $where[] = ["topic_id", "=", $id];

            $detail["is_join"] = false;

            $res = Db::name("user_topic")->where($where)->find();

            //是否加入
            if ($res) {
                $detail["is_join"] = true;
            }

            //是否管理员
            $detail["is_admin"] = false;
            $isAdmin = Db::name("topic_admin")->where($where)->find();
            if ($isAdmin) {
                $detail["is_admin"] = true;
            }
        }

        return message($detail);
    }

    //加入圈子
    public function joinTopic()
    {
        $userId = BaseService::getLoginUserId();
        $topicId = input("id");

        $data["user_id"] = $userId;
        $data["topic_id"] = $topicId;
        $data["create_time"] = time();
        $isjoinTopic = Db::name("user_topic")->where($data)->find();

        if ($isjoinTopic) {
            return error("您已加入圈子");
        }

        $res = Db::name("user_topic")->insert($data);

        if ($res) {
            Db::name("topic")->where("id", $topicId)->inc("user_num")->update();
            return message("加入成功");
        }
        return error("未知错误");

    }

    //创建圈子
    public function topicSave()
    {
        $userId = BaseService::getLoginUserId();
        $topicId = input("id");
        $data = input("post.");

        try {
            validate(\app\common\validate\Topic::class)->check($data);
        } catch (ValidateException $e) {
            return error($e->getError());
        }

        if ($topicId) {
            $res = TopicModel::update($data);
        } else {
            $data["id"] = BaseService::randomStr();
            $data["user_id"] = $userId;
            $res = TopicModel::create($data);
            $topicId = $res->id;

            Db::name("user_topic")->insert(["user_id" => $userId, "topic_id" => $topicId, "create_time" => time()]);
        }

        if ($res) {
            return message(["id" => $topicId], "保存成功");
        }

        return error("保存失败");
    }

    //查询圈子内用户列表
    public function userList()
    {
        $id = input("id");
        $userId = BaseService::getLoginUserIdNoAuth();
        $topicUid = Db::name("topic")->where("id", $id)->value("user_id");
        $uids = Db::name("user_topic")->where("topic_id", $id)->column("user_id");
        $list = UserModel::order("update_time desc")->where("id", "<>", $topicUid)->where("id", "in", $uids)->paginate(10)->each(function ($item) use ($id, $userId) {
            $where["user_id"] = $userId;
            $where["follow_uid"] = $item["id"];

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 0; //未关注
            }

            $isAdmin = Db::name("topic_admin")->where(["topic_id" => $id, "user_id" => $item["id"]])->find();
            if ($isAdmin) {
                $item["is_admin"] = true;
            } else {
                $item["is_admin"] = false;
            }
        });

        return message($list);
    }

    //解散圈子
    public function topicDel()
    {
        $id = input("id");
        $res = TopicModel::destroy($id);
        if ($res) {
            Db::name("user_topic")->where("topic_id", $id)->delete();//删除该圈子用户信息
            return message("删除成功");
        }
        return error("删除失败");
    }

    //退出圈子
    public function userQuit()
    {

        $topicId = input("id");
        $userId = BaseService::getLoginUserId();

        $where[] = ["user_id", "=", $userId];
        $where[] = ["topic_id", "=", $topicId];

        $topicAdminUid = TopicModel::find($topicId)["uid"];

        if ($topicAdminUid == $userId) {
            return error("圈主不可退出圈子");
        }

        $res = Db::name("user_topic")->where($where)->delete();

        if ($res) {
            Db::name("topic")->where("id", $topicId)->dec("user_num")->update();
            return message("已退出该圈子");
        }

        return error("操作失败");
    }
}